package com.huyong.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.huyong.dao.LoginDao;
import com.huyong.entity.UserLogin;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements com.huyong.service.LoginService {

    @Autowired
    private LoginDao loginDao;
    //登录方法
    @Override
    public boolean login(String username, String password){
        QueryWrapper<UserLogin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName",username);
        queryWrapper.eq("password",password);
        UserLogin userLogin = loginDao.selectOne(queryWrapper);
        if (userLogin!=null){
            return true;
        }else {
            return false;
        }
    }

    //注册方法
    @Override
    public boolean register(UserLogin userRegister){
        //这里需要先查找是否该账号已被注册
        String userRes = userRegister.getUserName();
        //从数据库中查找该用户名
        QueryWrapper<UserLogin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName",userRes);
        UserLogin userInDb = loginDao.selectOne(queryWrapper);

        //如果userInDb存在，则返回false，否则，存入数据库中，返回true
        if (userInDb!=null){
            return false;
        }else {
            int insert = loginDao.insert(userRegister);
            return insert==1?true:false;
        }
    }

    //重置密码
    public boolean forget(UserLogin userForget){
        //先查询该用户是否存在
        QueryWrapper<UserLogin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userName",userForget.getUserName());
        queryWrapper.eq("code",userForget.getCode());
        UserLogin userFind = loginDao.selectOne(queryWrapper);

        //若存在，则重置密码
        if (userFind!=null){
            userFind.setUserName(null).setCode(null).setPassword(userForget.getPassword());
            loginDao.update(userFind,queryWrapper);
            return true;
        }else {//若不存在，则前往注册
            return false;
        }
    }
}
